package com.ruoyi.system.service.aggregation.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.utils.RedisLockUtil;
import com.ruoyi.system.domain.aggregation.Account;
import com.ruoyi.system.domain.aggregation.Withdraw;
import com.ruoyi.system.mapper.aggregation.AccountMapper;
import com.ruoyi.system.mapper.aggregation.WithdrawMapper;
import com.ruoyi.system.service.aggregation.IWithdrawService;

/**
 * 提现Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-01
 */
@Service
public class WithdrawServiceImpl implements IWithdrawService 
{
    @Autowired
    private WithdrawMapper withdrawMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private RedisLockUtil redisLockUtil;

    @Override
    public Withdraw selectWithdrawById(Long id)
    {
        return withdrawMapper.selectWithdrawById(id);
    }

    @Override
    public List<Withdraw> selectWithdrawList(Withdraw withdraw)
    {
        return withdrawMapper.selectWithdrawList(withdraw);
    }

    /**
     * 提现申请
     * 优化：使用分布式锁防止重复提交
     */
    @Override
    @Transactional
    public void applyWithdraw(Long userId, Integer userType, Long amount)
    {
        // 🚀 优化：使用分布式锁防止重复提交
        String lockKey = "withdraw:apply:" + userId;
        String lockValue = null;
        
        try {
            lockValue = redisLockUtil.tryLock(lockKey, 10);
            if (lockValue == null) {
                throw new ServiceException("操作太频繁，请稍后再试");
            }
            
            // 查询账户
            Account account = accountMapper.selectAccountByUserId(userId);
            if (account == null)
            {
                throw new ServiceException("账户不存在");
            }

            // 验证可提现余额
            if (account.getBalance() < amount)
            {
                throw new ServiceException("可提现余额不足");
            }

            // 创建提现记录
            Withdraw withdraw = new Withdraw();
            withdraw.setId(System.currentTimeMillis()); // 生成ID
            withdraw.setUserId(userId);
            withdraw.setUserType(userType);
            withdraw.setAmount(amount);
            withdraw.setStatue(1); // 待审核
            withdraw.setDeleted(0);
            withdraw.setCreateTime(new Date());
            withdrawMapper.insertWithdraw(withdraw);

            // 冻结可提现余额（从可提现余额扣除）
            account.setBalance(account.getBalance() - amount);
            account.setUpdateTime(new Date());
            accountMapper.updateAccount(account);
            
        } finally {
            // 释放锁
            if (lockValue != null) {
                redisLockUtil.unlock(lockKey, lockValue);
            }
        }
    }

    /**
     * 提现审核
     * statue: 1待审核、2已通过、3已拒绝
     */
    @Override
    @Transactional
    public void checkWithdraw(Long id, Integer statue, String reason)
    {
        Withdraw withdraw = withdrawMapper.selectWithdrawById(id);
        if (withdraw == null)
        {
            throw new ServiceException("提现记录不存在");
        }

        if (withdraw.getStatue() != 1)
        {
            throw new ServiceException("提现状态不正确");
        }

        // 更新提现状态
        withdraw.setStatue(statue);
        withdraw.setReason(reason);
        withdraw.setUpdateTime(new Date());
        withdrawMapper.updateWithdraw(withdraw);

        // 如果拒绝，退回可提现余额
        if (statue == 3)
        {
            Account account = accountMapper.selectAccountByUserId(withdraw.getUserId());
            if (account != null)
            {
                account.setBalance(account.getBalance() + withdraw.getAmount());
                account.setUpdateTime(new Date());
                accountMapper.updateAccount(account);
            }
        }
        // 如果通过，调用支付宝转账
        else if (statue == 2)
        {
            // TODO: 调用支付宝转账接口
            System.out.println("提现审核通过，需要转账金额：" + withdraw.getAmount() + "分");
        }
    }

    /**
     * 编辑提现申请（被拒绝的申请可以修改后重新提交）
     */
    @Override
    @Transactional
    public void editWithdraw(Withdraw withdraw)
    {
        Withdraw existingWithdraw = withdrawMapper.selectWithdrawById(withdraw.getId());
        if (existingWithdraw == null)
        {
            throw new ServiceException("提现记录不存在");
        }

        // 只有被拒绝的申请才能修改
        if (existingWithdraw.getStatue() != 3)
        {
            throw new ServiceException("只有被拒绝的提现申请才能修改");
        }

        // 验证新的提现金额
        Account account = accountMapper.selectAccountByUserId(withdraw.getUserId());
        if (account == null)
        {
            throw new ServiceException("账户不存在");
        }

        // 计算金额变化
        Long amountDiff = withdraw.getAmount() - existingWithdraw.getAmount();
        
        // 如果新金额更大，检查余额是否足够
        if (amountDiff > 0 && account.getBalance() < amountDiff)
        {
            throw new ServiceException("可提现余额不足，差额：" + amountDiff + "分");
        }

        // 更新提现记录
        withdraw.setStatue(1); // 重置为待审核状态
        withdraw.setReason(null); // 清空拒绝原因
        withdraw.setUpdateTime(new Date());
        withdrawMapper.updateWithdraw(withdraw);

        // 调整账户余额
        if (amountDiff != 0)
        {
            account.setBalance(account.getBalance() - amountDiff);
            account.setUpdateTime(new Date());
            accountMapper.updateAccount(account);
        }
    }

    @Override
    public int updateWithdraw(Withdraw withdraw)
    {
        withdraw.setUpdateTime(DateUtils.getNowDate());
        return withdrawMapper.updateWithdraw(withdraw);
    }
}

